package models

import (
	"fmt"

	"Web-Shop/modules/utils"

	"github.com/astaxie/beego/orm"
)

func (m *User) Insert() error {
	if _, err := orm.NewOrm().Insert(m); err != nil {
		return err
	}
	return nil
}

func (m *User) Read(field ...string) error {
	o := orm.NewOrm()
	if err := o.Read(m, field...); err != nil {
		return err
	}
	return nil
}

func (m *User) ActiveFunc() error {
	m.Active = true
	o := orm.NewOrm()
	if _, err := o.Update(m); err != nil {
		return err
	}
	return nil
}

func (m *UserEmailRecord) Insert() error {
	m.Salt = utils.GetRandomString(20)
	if _, err := orm.NewOrm().Insert(m); err != nil {
		return err
	}
	return nil
}

func (m *UserEmailRecord) Read() error {
	o := orm.NewOrm()
	if err := o.Read(m, "Salt"); err != nil {
		return err
	}
	return nil
}

func (m *UserEmailRecord) ActiveFunc() error {
	m.Used = true
	o := orm.NewOrm()
	if _, err := o.Update(m); err != nil {
		return err
	}
	return nil
}

func (m *Address) Read(addr interface{}, user *User) {
	qs := orm.NewOrm().QueryTable("Address").RelatedSel("User").Filter("User__Name", user.Name)
	switch v := addr.(type) {
	case *Address:
		qs.Filter("Isdefault", true).One(v)
	case *[]*Address:
		fmt.Println("user.Name")
		qs.All(v)
	}
}

func (m *Address) Insert() error {
	o := orm.NewOrm()
	if _, err := o.QueryTable("Address").Filter("Isdefault", true).Update(orm.Params{
		"Isdefault": false,
	}); err != nil {
		return err
	}
	fmt.Println(1)
	if num, err := o.Insert(m); err != nil {
		fmt.Println(3)
		return err
	} else {
		fmt.Println("num",num)
	}
	
	fmt.Println(2)
	return nil
}

func (m *Address) Update() error {
	o := orm.NewOrm()
	if _, err := o.Update(m, "Id"); err != nil {
		return err
	}
	return nil
}
